package com.harboursoftware.xstorage.io;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.input.CountingInputStream;
import org.apache.commons.lang.math.LongRange;

import com.harboursoftware.xstorage.XStorageRuntimeException;

/**
 * 
 * @author Simon Leung
 * @since 0.1
 */
public class PostSpecifyingRangeInputStream extends CountingInputStream {
    private LongRange range;
    public PostSpecifyingRangeInputStream(InputStream in, long lower, long upper) {
        super(in);
        this.range = new LongRange(lower, upper);
    }

    /**
     * @inheritDoc
     * @throws XStorageRuntimeException
     */
    @Override
    public int read() throws IOException {
        int data = super.read();
        if(data == -1) {
            validateByteCount();
        }
        return data;
    }

    /**
     * @inheritDoc
     * @throws XStorageRuntimeException
     */
    @Override
    public void close() throws IOException {
        super.close();
        validateByteCount();
    }

    /**
     * 如果byteCount超过有效范围抛出异常
     */
    private void validateByteCount() {
        if(!range.containsLong(getByteCount())) {
            throw new XStorageRuntimeException();
        }
    }
}
